package pl.edu.pw.ee.buildcity.scheduler;

import org.apache.log4j.Logger;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.notifiers.AbstractNotifier;
import pl.edu.pw.ee.buildcity.services.BuildActivityService;

import javax.annotation.Resource;

/**
 * @author Mateusz
 * @since 2010-02-28
 */
public class BuildPostProcessing {

	private static final Logger log = Logger.getLogger(BuildPostProcessing.class);

	@Resource(name = "buildActivityService")
	private BuildActivityService buildActivityService;

	@Resource(name = "ggNotifier")
	private AbstractNotifier ggNotifier;

	@Resource(name = "mailNotifier")
	private AbstractNotifier mailNotifier;

	public void performPostProcessing(BuildContext ctx) {
		BuildActivity buildActivity = registerActivityFinish(ctx);
		performNotifications(buildActivity);
	}

	private BuildActivity registerActivityFinish(BuildContext ctx) {
		BuildActivity finishedBuildActivity = buildActivityService.registerActivityFinish(ctx.getBuildActivity(), ctx.getResult());
		return finishedBuildActivity;
	}

	private void performNotifications(BuildActivity buildActivity) {
		String emails = buildActivity.getBuildDefinition().getNotifiedEmails();
		log.info("Trying to notify e-mail recipients: " + emails);
		mailNotifier.notifyEndOfBuild(emails, buildActivity);

		String ggUins = buildActivity.getBuildDefinition().getNotifiedGG();
		log.info("Trying to notify GG recipients: " + ggUins);
		ggNotifier.notifyEndOfBuild(ggUins, buildActivity);
	}
}
